<script setup>
import { ref, onMounted } from 'vue'
import { Map, View } from 'ol'
import TileLayer from 'ol/layer/Tile'
import XYZ from 'ol/source/XYZ'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import { Draw } from 'ol/interaction'
import { GeoJSON } from 'ol/format'
import { Style, Fill, Stroke, Circle as CircleStyle } from 'ol/style'
import 'ol/ol.css'
import * as turf from '@turf/turf'

const mapRef = ref(null)
const map = ref(null)
const vectorSource = ref(null)
const vectorLayer = ref(null)
const bufferSource = ref(null)
const bufferLayer = ref(null)
const drawInteraction = ref(null)
const isDrawing = ref(false)
const drawType = ref('Polygon')
const hasFeatures = ref(false)
const bufferDistance = ref(10)
const bufferUnit = ref('kilometers')

// 绘制样式
const drawStyle = new Style({
  fill: new Fill({ color: 'rgba(255, 255, 255, 0.2)' }),
  stroke: new Stroke({ color: '#ffcc33', width: 2 }),
  image: new CircleStyle({ radius: 7, fill: new Fill({ color: '#ffcc33' }) })
})

// 缓冲区结果样式
const bufferStyle = new Style({
  fill: new Fill({ color: 'rgba(0, 150, 255, 0.3)' }),
  stroke: new Stroke({ color: '#0096ff', width: 2 })
})

// 开始绘制
const startDrawing = () => {
  if (isDrawing.value) {
    stopDrawing()
    return
  }
  
  isDrawing.value = true
  
  // 创建矢量数据源
  vectorSource.value = new VectorSource()
  
  // 创建矢量图层
  vectorLayer.value = new VectorLayer({
    source: vectorSource.value,
    style: drawStyle
  })
  
  // 添加矢量图层到地图
  map.value.addLayer(vectorLayer.value)
  
  // 创建绘图交互
  drawInteraction.value = new Draw({
    source: vectorSource.value,
    type: drawType.value
  })
  
  // 添加绘图交互到地图
  map.value.addInteraction(drawInteraction.value)
  
  // 监听绘图结束事件
  drawInteraction.value.on('drawend', () => {
    hasFeatures.value = true
  })
}

// 停止绘制
const stopDrawing = () => {
  if (drawInteraction.value) {
    map.value.removeInteraction(drawInteraction.value)
    drawInteraction.value = null
  }
  isDrawing.value = false
}

// 清除绘制
const clearDrawing = () => {
  if (vectorSource.value) {
    vectorSource.value.clear()
    hasFeatures.value = false
  }
  
  if (isDrawing.value) {
    stopDrawing()
  }
}

// 计算缓冲区
const calculateBuffer = () => {
  if (!vectorSource.value || vectorSource.value.getFeatures().length === 0) {
    return
  }
  
  // 清除之前的缓冲区结果
  if (bufferSource.value) {
    bufferSource.value.clear()
  }
  
  // 获取绘制的要素
  const features = vectorSource.value.getFeatures()// 获取所有绘制的要素
  const format = new GeoJSON()// 用于转换OpenLayers要素为GeoJSON
  
  // 遍历所有要素，计算缓冲区
  features.forEach(feature => {
    // 将OpenLayers要素转换为GeoJSON
    const geoJson = format.writeFeatureObject(feature, {
      featureProjection: 'EPSG:4326',
      dataProjection: 'EPSG:4326'
    })
    
    // 使用Turf.js计算缓冲区
    const buffered = turf.buffer(geoJson, bufferDistance.value, {
      units: bufferUnit.value
    })
    
    // 将Turf.js结果转换为OpenLayers要素
    const bufferFeature = format.readFeature(buffered, {
      featureProjection: 'EPSG:4326',
      dataProjection: 'EPSG:4326'
    })
    
    // 添加到缓冲区结果图层
    bufferSource.value.addFeature(bufferFeature)
  })
}

// 清除缓冲区结果
const clearBuffer = () => {
  if (bufferSource.value) {
    bufferSource.value.clear()
  }
}

onMounted(() => {
  // 初始化地图
  map.value = new Map({
    target: mapRef.value,
    layers: [
      new TileLayer({
        source: new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}',
          crossOrigin: 'anonymous'
        })
      })
    ],
    view: new View({
      center: [104, 35], // 地图中心坐标（经度，纬度）- 设置为中国中心
      zoom: 5,         // 初始缩放级别
      projection: 'EPSG:4326' // 使用WGS84坐标系
    })
  })
  
  // 创建缓冲区结果数据源
  bufferSource.value = new VectorSource()
  
  // 创建缓冲区结果图层
  bufferLayer.value = new VectorLayer({
    source: bufferSource.value,
    style: bufferStyle
  })
  
  // 添加缓冲区结果图层到地图
  map.value.addLayer(bufferLayer.value)
})
</script>

<template>
  <div class="map-container">
    <!-- <div class="header">
    </div> -->
    <div class="controls">
      <!-- 绘制控制 -->
      <div class="control-group">
        <h3>绘制控制</h3>
        <div class="button-group">
          <button @click="startDrawing" :class="{ active: isDrawing }">
            {{ isDrawing ? '停止绘制' : '开始绘制' }}
          </button>
          <button @click="clearDrawing" :disabled="!hasFeatures && !isDrawing">
            清除绘制
          </button>
          <select v-model="drawType" :disabled="isDrawing">
            <option value="Point">点</option>
            <option value="LineString">线</option>
            <option value="Polygon">面</option>
          </select>
        </div>
      </div>
      
      <!-- 缓冲区参数设置 -->
      <div class="control-group">
        <h3>缓冲区参数</h3>
        <div class="parameter-group">
          <div class="parameter-item">
            <label for="distance">距离:</label>
            <input 
              type="number" 
              id="distance" 
              v-model.number="bufferDistance" 
              min="0.1" 
              step="0.1"
            >
            <select v-model="bufferUnit">
              <option value="meters">米</option>
              <option value="kilometers">千米</option>
              <option value="miles">英里</option>
              <option value="feet">英尺</option>
            </select>
          </div>
          <div class="parameter-item">
            <input 
              type="range" 
              v-model.number="bufferDistance" 
              min="0.1" 
              max="100" 
              step="0.1"
            >
            <span class="range-value">{{ bufferDistance }} {{ bufferUnit }}</span>
          </div>
        </div>
        <div class="button-group">
          <button @click="calculateBuffer" :disabled="!hasFeatures">
            执行缓冲区分析
          </button>
          <button @click="clearBuffer">
            清除结果
          </button>
        </div>
      </div>
    </div>
    <div ref="mapRef" class="map"></div>
  </div>
</template>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: row;
  font-family: Arial, sans-serif;
  background-color: #f5f5f5;
  overflow: hidden;
}

.header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100;
}

h1 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.controls {
  width: 280px;
  height: calc(100vh - 60px);
  margin-top: 60px;
  background-color: white;
  padding: 15px;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  z-index: 50;
}

.control-group {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.control-group:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.control-group h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  color: #555;
}

.button-group {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
  flex-wrap: wrap;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}

button.active {
  background-color: #f44336;
}

button.active:hover {
  background-color: #d32f2f;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

select {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
  background-color: white;
}

.parameter-group {
  margin-bottom: 15px;
}

.parameter-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.parameter-item label {
  font-weight: bold;
  color: #555;
  min-width: 60px;
}

.parameter-item input[type="number"] {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100px;
  font-size: 14px;
}

.parameter-item input[type="range"] {
  flex: 1;
  min-width: 200px;
}

.range-value {
  min-width: 120px;
  font-weight: bold;
  color: #333;
}

.map {
  flex: 1;
  height: 100vh;
  border: none;
  border-radius: 0;
  box-shadow: none;
  background-color: white;
  margin-top: 60px;
}
</style>